import json
import os

from server_o import UserManager, DataStorage

TEST_USERS_FILE = 'users.json'
TEST_USAGE_FILE = 'user_usage_data.json'


def create_test_usage_file():
    """Create a temporary usage data file for testing."""
    test_data = {
        "Alice": [
            "11101",
            ["4.29", {"TikTok": 0.5, "Youtube": 0.5, "Instagram": 1.2, "Total": 8.4}],
            ["4.30", {"TikTok": 0.6, "Youtube": 0.7, "Instagram": 1.3, "Total": 9.0}]
        ],
        "Bob": [
            "11102",
            ["4.30", {"TikTok": 0.4, "Youtube": 0.6, "Instagram": 1.0, "Total": 8.0}]
        ]
    }
    with open(TEST_USAGE_FILE, 'w') as f:
        json.dump(test_data, f, indent=2)


def cleanup_test_files():
    """Remove test files after testing."""
    if os.path.exists(TEST_USERS_FILE):
        os.remove(TEST_USERS_FILE)
    if os.path.exists(TEST_USAGE_FILE):
        os.remove(TEST_USAGE_FILE)


def test_user_manager():
    """Test UserManager functionality."""
    print("Starting UserManager tests...\n")

    # Create test usage data file
    create_test_usage_file()

    # Initialize UserManager and load users
    manager = UserManager()

    # Check if users are loaded correctly
    print("Users in UserManager:")
    for name, user_id in manager.users.items():
        print(f"{name}: {user_id}")

    # Check if user usage data is loaded
    print("\nUser usage data:")
    for name, data in manager.user_data.items():
        print(f"{name}:")
        print(json.dumps(data, indent=2))

    # Cleanup
    cleanup_test_files()
    print("\nTests completed and test files cleaned up.")


if __name__ == '__main__':
    test_user_manager()
